import DrawerFooter from '@/components/DrawerFooter';
import { useStore } from '@/hooks';
import { Button, Form } from '@alifd/next';
import { t } from '@lingui/macro';
import React, { useEffect, useRef, useState } from 'react';
import { FieldsGrid, TitleGrid } from '../stores/definitions';
import { observer } from 'mobx-react-lite';
import RoadDetailInfo from './RoadDetailInfo';
import MerchantSurchargesInfo from './MerchantSurchargesInfo';
import TauTable from '@/components/TauTable';
import styles from './CcOrderForm.module.scss';

const FromItem = Form.Item;

function CcOrderForm({ orderId, modal, onCancel, handleCancel }) {
  const { ccOrderStore: store } = useStore();
  const [formData, setFormData] = useState({});
  const [isViewMode] = useState(modal[0] === 'view');
  const formProps = isViewMode ? { field: false } : {};
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改

  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    (async () => {
      const order = await store.get(orderId);
      const task = await store.getTask(order);
      const formDataTmp = { ...order, TASK: task }
      if (order?.merchant) {
        const merchantInfo = await store.getMerchantInfo(order?.merchant);
        _.assign(formDataTmp, { MERCHANT: merchantInfo });
      }
      editCtx.origin = _.cloneDeep(order);
      setFormData(formDataTmp);
    })();
  }, [orderId]);

  if (!formData) return <></>;

  const overrideModel = {
    discountInfos: {
      ui: {
        renderer: (v) => {
          return (
            <TauTable
              dataSource={v}
              primaryKey="couponId"
              hidePagination
              hasBorder={false}
              className={styles.discountInfos_table}
              columns={[
                { title: '活动名称', dataIndex: 'activityName' },
                { title: '活动Id', dataIndex: 'activityId' },
                { title: '优惠券名称', dataIndex: 'couponName' },
                { title: '优惠券Id', dataIndex: 'couponId' },
                { title: '优惠券金额', dataIndex: 'discountPrice' },
                { title: '优惠券成本', dataIndex: 'cost' },
              ]}
            />
          );
        },
      },
    },
  };

  return (
    <Form
      inline
      isPreview={isViewMode}
      {...formProps}
      value={formData}
      useLabelForErrorMessage
      onCancel={onCancel}
    >
      <TitleGrid title={t`基本信息`} />
      <FieldsGrid
        formData={formData}
        mode={modal[0]}
        fields={['orderNumber', 'ccOrder.orderStatus', 'company.name',
          'originalPrice', 'price', 'discountPriceTotal', 'crDate',
          'ccOrder.payType', 'ccOrder.payTime', 'ccOrder.priceDifference',
          'orderTypeName', 'source', 'attributionName', 'receiveName', 'ccOrder.language', 'orderOptionTypeName',
          'currency', 'refundInfos[0].state', 'refundInfos[0].refundPrice']}
      />

      <TitleGrid title={t`优惠信息`} />
      <FieldsGrid
        formData={formData}
        mode={modal[0]}
        overrideModel={overrideModel}
        fields={['discountInfos']}
      />

      <TitleGrid title={t`客户资料`} />
      <FieldsGrid
        formData={formData}
        mode="view"
        fields={['ccOrder.passengerName', 'ccOrder.passengerPhone', 'ccOrder.subscribeName', 'ccOrder.subscribePhone', 'partnerName']}
      />

      <TitleGrid title={t`乘坐信息`} />
      <FieldsGrid
        formData={formData}
        mode="view"
        fields={['beginAreaName', 'ccOrder.beginName', 'endAreaName', 'ccOrder.endName', 'ccOrder.predictBeginDate', 'ccOrder.predictTime', 'ccOrder.mileage', 'ccOrder.isPass', 'ccOrder.isMap', 'ccOrder.number', 'ccOrder.flightNumber', 'ccOrder.numberOfLuggage']}
      />

      <TitleGrid title={t`承运信息`} />
      <RoadDetailInfo
        formData={formData}
      />

      <MerchantSurchargesInfo
        formData={formData}
      />


      <TitleGrid title={t`备注及照片`} />
      <FieldsGrid
        formData={formData}
        mode="view"
        fields={['remark', 'ccOrder.remarks', 'refundInfos[0].cancelRemark', 'orderChangeRemarks']}
      />

      <DrawerFooter>
        <FromItem>
          <Button style={{ marginLeft: 8 }} onClick={onCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
    </Form >
  );
}

export default observer(CcOrderForm);

